package org.xg.study.spring.al.controller;

import com.alibaba.csp.sentinel.annotation.SentinelResource;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xg.study.spring.al.config.BaseController;
import org.xg.study.spring.al.config.RestCodeEnum;
import org.xg.study.spring.al.config.RestException;
import org.xg.study.spring.al.pojo.Users;
import org.xg.study.spring.al.service.IUserService;

/**
 * @author CMG
 * @version 1.0
 * @description
 * @cLassName UserController
 * @date 2021/10/25 16:15
 **/
@RestController
@RequestMapping("/api/user")
public class UserController {
    @Reference
    private IUserService service;

    /**
     * 获取用户信息
     */
    @PostMapping("/userInfo")
    public String userInfo() {
        Users user = service.userInfo("");
        return JSON.toJSONString(user);
    }

    /**
     * 测试流控规则
     */
    @PostMapping("/testFlow")
    @SentinelResource(value = "user-testFlow",
            blockHandlerClass = UserBlockHandler.class, //对应异常类
            blockHandler = "handleException",  //只负责sentinel控制台配置违规
            fallback = "handleError",   //只负责业务异常
            fallbackClass = UserBlockHandler.class)
    public String testFlow() {
        Users user = service.userInfo("");
        return JSON.toJSONString(user);
    }

    /**
     * 测试降级规则
     */
    @PostMapping("/testDegrade")
    @SentinelResource(value = "user-testDegrade",
            blockHandlerClass = UserBlockHandler.class, //对应异常类
            blockHandler = "handleException",  //只负责sentinel控制台配置违规
            fallback = "handleError",   //只负责业务异常
            fallbackClass = UserBlockHandler.class)
    public String testDegrade() {
        Users user = service.userInfo("");
        return JSON.toJSONString(user);
    }

    @PostMapping("/deleteSource")
    public String deleteSource(@RequestBody JSONObject body) {
        String sqlCode = body.getString("sqlCode");
        if (StringUtils.isBlank(sqlCode)) {
            throw new RestException(RestCodeEnum.ERROR);//异常信息直接抛出
        }
        if (true) {
            return BaseController.success();//成功信息返回
        }
        return BaseController.error(RestCodeEnum.ERROR);//错误信息返回
    }
}
